/* eslint-disable eqeqeq */
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import List from '../components/user/List.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      component: Login
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          component: Welcome
        },
        {
          path: '/user/list',
          component: List
        }
      ]
    }
  ]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next是一个函数,代表放行

  // eslint-disable-next-line eqeqeq
  if (to.path == '/login') return next()
  if (to.path == '/register') return next()
  if (to.path == '/findPassword') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有登录
  if (!tokenStr) return next('/login')
  // 能走到这里说明这个token字符串是存在的
  next()
})

export default router
